package asyncudp;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;

/**
 * Callback ( write, get )
 */
public class TheMomentClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    @Override
    public void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
        String response = msg.content().toString(CharsetUtil.UTF_8);

        System.out.println("[LOG]: Receive message from the server.");

        if (response.startsWith("[ACK]")) {
            System.out.println("[SERVER]: " + response);
        } else if (response.startsWith("[BEAT]")) {
            System.out.println("[LOG]: Server is keeping alive ...");
        } else if (response.startsWith("[SERVER]")) {
            System.out.println(response);
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}